package handlers

import (
	"github.com/gin-gonic/gin"
	"img-text-mgr/models"
	"img-text-mgr/pkg"
	"strconv"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号不存在",
		})
		return
	}

	if pkg.Md5Str(password) != user.Password {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}

	token := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": token,
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "1"))
	offset := (page - 1) * size

	var count int64
	models.DB.Model(models.Imt{}).Count(&count)

	var imt []models.Imt
	err := models.DB.Offset(offset).Limit(size).Find(&imt).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"imt":   imt,
		},
	})
	return
}
